package ess.hardware;

public class Door implements MotoredComponent{

	Motor doorMotor;
	DoorClosingSensor doorSensor;
	Elevator elevator;
	float position;
	float gap; // 0 means closed, 1 means opened
	
	static float GAP_CLOSED = 0.0f;
	static float GAP_OPENED = 1.0f;
	
	public Door(Elevator elevator, DoorClosingSensor doorSensor)
	{
		this.elevator = elevator;
		this.doorSensor = doorSensor;  
		doorMotor = new Motor(this, 50, (float) 0.05);
	}
	
	public boolean moveMotoredComponent(int direction, float degree) {
		
		if(direction == Motor.MOTOR_OPERATION_OPEN)
		{
			if(gap > GAP_OPENED)
			{
				gap = GAP_OPENED;
				doorSensor.postEvent(new DoorClosingSensorEvent(elevator, DoorClosingSensor.DOOR_OPENED));
				stop();
			}
			else
			{
				gap += degree;
			}
		}
		else if(direction == Motor.MOTOR_OPERATION_CLOSE)
		{
			if(gap < GAP_CLOSED)
			{
				gap = GAP_CLOSED;
				doorSensor.postEvent(new DoorClosingSensorEvent(elevator, DoorClosingSensor.DOOR_CLOSED));
				stop();
			}
			else
			{
				gap -= degree;
			}
		}
		elevator.repaint();
		return false;
	}
	
	public void open()
	{
		doorMotor.move(Motor.MOTOR_OPERATION_OPEN);
	}
	
	public void close()
	{
		doorMotor.move(Motor.MOTOR_OPERATION_CLOSE);
	}
	
	public void stop()
	{
		doorMotor.stop();
	}
	
	public float getGap()
	{
		return gap;
	}

}
